package net.cassandraview.db;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;

public class RbcExportData implements Iterable<Map<String, String>> {

    private Logger log = Logger.getLogger(getClass().getName());
    private List<String> headers;
    private List<Map<String, String>> data = new ArrayList<Map<String, String>>();
    
    RbcExportData(InputStream in) {
        try {
            String line;
            boolean firstLine = true;
            BufferedReader reader = new BufferedReader(new InputStreamReader(in));
            while ((line = reader.readLine()) != null) {
                if (firstLine) {
                    firstLine = false;
                    headers = Arrays.asList(line.split("\\t"));
                } else {
                    String[] values = line.split("\\t");
                    Map<String, String> row = new HashMap<String, String>();
                    for (int i=0; i < headers.size(); i++) {
                        row.put(headers.get(i), values[i]);
                    }
                    data.add(row);
                }
            }
        } catch (IOException e) {
            log.log(Level.SEVERE, "Cannot read response from remote server.");
        } catch (ArrayIndexOutOfBoundsException e) {
            log.log(Level.SEVERE, "Incorrect response format.", e);
        }
    }
    
    Map<String, String> getNthLine(int n) {
        return data.get(n);
    }

    int getLinesCount() {
        return data.size();
    }

    public List<String> getHeaders() {
        return Collections.unmodifiableList(headers);
    }

    @Override
    public String toString() {
        String result = "";
        for (String header : headers) {
            result += header + "\t";
        }
        result += "\n";
        for (Map<String, String> row : data) {
            for (String header : headers) {
                result += row.get(header) + "\t";
            }
            result += "\n";
        }
        return result;
    }

    @Override
    public Iterator<Map<String, String>> iterator() {
        return data.iterator();
    }
}